package com.cb.admin.controllers;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cb.admin.domain.MemuInfo;
import com.cb.admin.domain.RoleInfo;
import com.cb.admin.domain.RoleMenuRef;
import com.cb.admin.service.IMemuInfoService;
import com.cb.admin.service.IRoleInfoService;
import com.cb.admin.service.IRoleMenuRefService;
import com.cb.constants.Constants;
import com.cb.util.DateUtils;
import com.cb.util.JSONUtil;


@Controller
@RequestMapping("/roleInfo")
public class RoleInfoController extends BaseController {

	private static Logger logger = Logger.getLogger(RoleInfoController.class.getName());

	@Autowired
	private IRoleInfoService roleInfoService;

	@Autowired
	private IMemuInfoService memuInfoService;

	@Autowired
	private IRoleMenuRefService roleMenuRefService;

	@RequestMapping("show")
	public String show(Model model) {
		return "role/roleInfoList";
	}

	@RequestMapping(path = "/getList", method = RequestMethod.POST)
	@ResponseBody
	public String getList(RoleInfo roleInfo) {
		//当前页  
		roleInfo.setStart((roleInfo.getPage()-1)*roleInfo.getRows());
		roleInfo.setLength(roleInfo.getRows());
		
		List<RoleInfo> arr = roleInfoService.query(roleInfo);

		JSONObject jo = new JSONObject();

		int size = roleInfoService.querySize(roleInfo);

		jo.put("rows", arr);
		jo.put("total", size);

		return jo.toString();
	}

	@RequestMapping("roleRefMenuInit")
	@ResponseBody
	public String roleRefMenuInit(@RequestParam("menuIds") String menuIds) {
		JSONObject jo = new JSONObject();

		List<MemuInfo> menu = memuInfoService.getAll();

		List<Map> ret = new ArrayList<Map>();

		for (MemuInfo menuInfo : menu) {

			Map map = new HashMap();

			map.put("id", menuInfo.getId());
			map.put("pId", menuInfo.getParentId());
			map.put("name", menuInfo.getDescs());
			map.put("open", true);

			if (menuIds != null && menuIds.length() > 0 && (","+menuIds).indexOf(","+menuInfo.getId()+",") != -1) {
				map.put("checked", true);
			} else {
				map.put("checked", false);
			}

			ret.add(map);

		}

		jo.put("ret", ret);

		return jo.toString();
	}

	@RequestMapping("createPage")
	public String createPage(Model model) {
		return "role/roleInfoDetail";
	}

	@RequestMapping(path = "/create", method = RequestMethod.POST)
	@ResponseBody
	public String create(RoleInfo role, HttpServletRequest request,HttpSession session) {

		JSONObject jo = new JSONObject();

		jo.put("returnFlag", Constants.returnObj.returnFlag_true);

		int cnt = roleInfoService.queryByName(role.getName());

		if (cnt > 0) {
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
			jo.put("code", Constants.returnObj.returnCode.code_1);
			return jo.toString();
		}

		role.setDeleteFlag(Constants.deleteFlag.deleteFlag_1);
		role.setCreateAt(DateUtils.getNowTime());
		role.setCreateUser(returnSessionObj(session).getAccount());
		role.setUpdateAt(DateUtils.getNowTime());
		role.setUpdateUser(returnSessionObj(session).getAccount());

		try {
			int roleId= roleInfoService.insert(role);
		} catch (Exception e) {
			JSONUtil.returnFailReuslt(null);
		}

		return jo.toString();
	}

	@RequestMapping("edit")
	public String edit(Model model, @RequestParam("id") int id) {
		RoleInfo role = roleInfoService.queryById(id);

		model.addAttribute("roleInfo", role);
		return "role/roleInfoEdit";
	}

	@RequestMapping(path = "/update", method = RequestMethod.POST)
	@ResponseBody
	public String update(RoleInfo role, HttpServletRequest request, HttpSession session) {
		JSONObject jo = new JSONObject();

		jo.put("returnFlag", Constants.returnObj.returnFlag_true);

		role.setUpdateAt(DateUtils.getNowTime());
		role.setUpdateUser(returnSessionObj(session).getAccount());

		try {
			roleInfoService.update(role);
		} catch (Exception e) {
			JSONUtil.returnFailReuslt(null);
		}

		return jo.toString();

	}

	@RequestMapping("deleteById")
	@ResponseBody
	public String deleteById(Model model,@RequestParam("Ids") String Ids) {
		
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		for(String id :Ids.split(",")){
			roleInfoService.deleteById(Integer.parseInt(id));
			roleMenuRefService.deleteByRoleId(Integer.parseInt(id));
		}
		
		return jo.toString();
	}

	@RequestMapping("roleRefMenuEdit")
	public String roleRefMenuEdit(Model model, @RequestParam("roleId") int roleId) {
		RoleInfo roleInfo = roleInfoService.queryById(roleId);

		String menuIds = formMenuIdsByRoleId(roleId);

		model.addAttribute("roleId", roleInfo.getId());
		model.addAttribute("menuIds", menuIds);
		return "role/roleRefMenuEdit";
	}	

	@RequestMapping("updateRoleMenuRef")
	@ResponseBody
	public String updateRoleMenuRef(@RequestParam("roleId")int roleId, @RequestParam("menuIds")String menuIds) {
		JSONObject jo = new JSONObject();
		
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		try {
			roleMenuRefService.deleteByRoleId(roleId);
			
			createRoleMenuRef(menuIds,roleId);
		} catch (Exception e) {
			JSONUtil.returnFailReuslt(null);
		}
		
		return jo.toString();
	}
	
	private String formMenuIdsByRoleId(int roleId) {
		List<String> arrMenuIds = roleMenuRefService.getMenuIdsByRoleId(roleId);

		String menuIds = "";
		for (String menuId : arrMenuIds) {
			menuIds += menuId + ',';
		}
				
		return menuIds;
	}
	
	private void createRoleMenuRef(String menuIds, int roleId) {
		if (menuIds != null && menuIds.length() > 0) {
			for (String menuId : menuIds.split(",")) {
				RoleMenuRef roleMenuRef = new RoleMenuRef();

				roleMenuRef.setRoleId(roleId);
				roleMenuRef.setMenuId(Integer.parseInt(menuId));

				roleMenuRefService.insert(roleMenuRef);
			}
		}
	}
}